from rest_framework.decorators import api_view
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

from rest_framework import mixins
from rest_framework import generics

from django.http import Http404

from django.utils import timezone
from article.models import Article, Category, Tag, Avatar
# from article.serializers import ArticleListSerializer, ArticleDetailSerializer

from article.permissions import IsAdminUserOrReadOnly

# Create your views here.
# @api_view(['GET', 'POST'])
# def article_list(request):
#   if request.method == 'GET':
#     articles = Article.objects.all()
#     serializer = ArticleListSerializer(articles, many=True)
#     return Response(serializer.data)
  
#   serializer = ArticleListSerializer(data=request.data)
#   if serializer.is_valid():
#     serializer.save()
#     return Response(serializer.data, status=status.HTTP_201_CREATED)
#   return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

# class ArticleList(generics.ListCreateAPIView):
#     queryset = Article.objects.all()
#     serializer_class = ArticleListSerializer

#     # 只准许管理员发布文章
#     permission_classes = [IsAdminUserOrReadOnly]

#     def perform_create(self, serializer):
#       serializer.save(author=self.request.user)

# class ArticleDetail(APIView):
#   """文章详情视图"""
#   def get_object(self, pk):
#     try:
#       return Article.objects.get(pk=pk)
#     except:
#       raise Http404
  
#   def get(self, request, pk):
#     article = self.get_object(pk)
#     serializer = ArticleDetailSerializer(article)
#     return Response(serializer.data)
  
#   def put(self, request, pk):
#     article = self.get_object(pk)
#     request.data['id'] = pk
#     serializer = ArticleDetailSerializer(article, data=request.data)
#     # 验证提交的数据是否合法
#     # 不合法则返回400
#     if serializer.is_valid():
#       # 序列化器将持有的数据反序列化后，
#       # 保存到数据库中
#       serializer.save()
#       return Response(serializer.data)
#     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
  
#   def delete(self, request, pk):
#     article = self.get_object(pk)
#     article.delete()
#     return Response(status=status.HTTP_204_NO_CONTENT)

# class ArticleDetail(generics.RetrieveUpdateDestroyAPIView):
#   """文章详情视图"""
#   queryset = Article.objects.all()
#   serializer_class = ArticleDetailSerializer

#   permission_classes = [IsAdminUserOrReadOnly]

  # def get(self, request, *args, **kwargs):
  #   return self.retrieve(request, *args, **kwargs)
  
  # def put(self, request, *args, **kwargs):
  #   return self.update(request, *args, **kwargs)
  
  # def delete(self, request, *args, **kwargs):
  #   return self.delete(request, *args, **kwargs)

from rest_framework import viewsets
from django_filters.rest_framework import DjangoFilterBackend
# 模糊搜索
from rest_framework import filters

from article.serializers import ArticleSerializer, ArticleDetailSerializer, CategorySerializer, CategoryDetailSerializer, TagSerializer, AvatarSerializer

class ArticleViewSet(viewsets.ModelViewSet):
  queryset = Article.objects.all()
  serializer_class = ArticleSerializer
  permission_classes = [IsAdminUserOrReadOnly]

  filter_backends = [DjangoFilterBackend]
  # filterset_fields = ['author__username', 'title']

  # 模糊搜索
  filter_backends = [filters.SearchFilter]
  search_fields = ['title']

  def perform_create(self, serializer):
    serializer.save(author=self.request.user)

  def get_queryset(self):
    queryset = self.queryset
    username = self.request.query_params.get('username', None)
    if username is not None:
      queryset = queryset.filter(author__username=username)
    
    return queryset
  
  def get_serializer_class(self):
    if self.action == 'list':
      return ArticleSerializer
    return ArticleDetailSerializer

class CategoryViewSet(viewsets.ModelViewSet):
  """分类视图集"""
  queryset = Category.objects.all()
  serializer_class = CategorySerializer
  permission_classes = [IsAdminUserOrReadOnly]

  def get_serializer_class(self):
    if self.action == 'list':
      return CategorySerializer
    return CategoryDetailSerializer

  def perform_create(self, serializer):
    serializer.save(create_by=self.request.user, modifier=self.request.user)

  def perform_update(self, serializer):
    serializer.update(modifier=self.request.user, modified=timezone.now())

class TagViewSet(viewsets.ModelViewSet):
  queryset = Tag.objects.all()
  serializer_class = TagSerializer
  permission_classes = [IsAdminUserOrReadOnly]

  def perform_create(self, serializer):
    serializer.save(creator=self.request.user, modifior=self.request.user)
  
  def perform_update(self, serializer):
    serializer.update( modifior=self.request.user, modified=timezone.now())

class AvatarViewSet(viewsets.ModelViewSet):
  queryset = Avatar.objects.all()
  serializer_class = AvatarSerializer
  permission_classes = [IsAdminUserOrReadOnly]
